package util;

import entity.User;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.HashSet;

public class GUIUtil {
    private static String lastUsedDirectory = ".";
    public static final HashSet<String> typeSupport = JsonRW.getStringSet(JsonRW.configFile, "imageTypeSupport");

    /**
     * 设置文件选择器
     * @param title 标题
     * @param typeSupport 支持的文件类型，以字符串HashSet集合传入
     * @return 文件选择结果
     */
    public static JFileChooser setAndGetFileChooser(String title, HashSet<String> typeSupport) {
        Object obj = JsonRW.get(JsonRW.historyFile, "lastUsedDirectory");
        if (obj == null) {
            JsonRW.set(JsonRW.historyFile, "lastUsedDirectory", ".");
        } else {
            lastUsedDirectory = (String) obj;
        }

        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle(title);
        fileChooser.setCurrentDirectory(new File(lastUsedDirectory));
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

        if (typeSupport != null) {
            for (String type : typeSupport) {
                FileFilter filter = new FileNameExtensionFilter(type.toUpperCase() + "文件（*." + type + "）", type);
                fileChooser.addChoosableFileFilter(filter);
            }
        }
        return fileChooser;
    }

    public static JLabel createAvatarLabel(String username, int size) {
        JLabel avatarLabel = new JLabel(new ImageIcon(Inner(username, size)));
        avatarLabel.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));
        return avatarLabel;
    }

    // 创建用户信息标签的公共方法
    public static JLabel createUserLabel(User user, Font font) {
        JLabel userLabel = new JLabel("用户名: " + user.getUsername());
        userLabel.setFont(font);
        userLabel.setBorder(new EmptyBorder(0, 10, 0, 0));
        return userLabel;
    }

    // 刷新头像的公共方法
    public static void refreshAvatar(JLabel avatarLabel, String username, int size) {
        avatarLabel.setIcon(new ImageIcon(Inner(username, size)));
    }

    private static Image Inner(String username, int size) {
        String filename = JsonRW.getStr(JsonRW.configFile, "userDataDir") + "/" + username + "/avatar/0.png";
        File avatarFile = new File(filename);
        if (!avatarFile.exists()) {
            filename = JsonRW.getStr(JsonRW.configFile, "defaultAvatar");
        }
        ImageIcon originalIcon = new ImageIcon(filename);
        return originalIcon.getImage().getScaledInstance(size, size, Image.SCALE_SMOOTH);
    }

    public static <T extends Window> void showFileSelectionDialog(T parent, String title, FileHandler fileHandler) {
        JTextField pathField = new JTextField(30);
        JButton browseButton = new JButton("从文件夹中选择");

        JPanel panel = new JPanel(new BorderLayout(5, 5));
        JPanel inputPanel = new JPanel(new BorderLayout(5, 5));

        inputPanel.add(new JLabel("文件路径:"), BorderLayout.WEST);
        inputPanel.add(pathField, BorderLayout.CENTER);
        inputPanel.add(browseButton, BorderLayout.EAST);

        panel.add(inputPanel, BorderLayout.CENTER);

        // 文件选择事件
        browseButton.addActionListener(_ -> {
            JFileChooser fileChooser = GUIUtil.setAndGetFileChooser(title, GUIUtil.typeSupport);
            if (fileChooser.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) {
                File selectedFile = fileChooser.getSelectedFile();
                pathField.setText(selectedFile.getAbsolutePath());
                lastUsedDirectory = selectedFile.getParent();
                JsonRW.set(JsonRW.historyFile, "lastUsedDirectory", selectedFile.getParent());
            }
        });

        // 显示对话框
        int option = JOptionPane.showConfirmDialog(parent, panel, title, JOptionPane.OK_CANCEL_OPTION);

        if (option == JOptionPane.OK_OPTION && !pathField.getText().trim().isEmpty()) {
            String filePath = pathField.getText().trim().replace("\"", "").replace("\\", "/");

            File selectedFile = new File(filePath);
            if (selectedFile.exists()) {
                try {
                    fileHandler.handle(filePath);
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(parent, "处理文件时出错: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(parent, "文件不存在！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    public static JButton createButton(String text, ActionListener listener) {
        JButton button = new JButton(text);
        button.addActionListener(listener);
        return button;
    }

    // 创建样式化标签
    public static JLabel createStyledLabel(String text, int fontSize, Color color) {
        JLabel label = new JLabel(text, SwingConstants.CENTER);
        label.setFont(new Font("微软雅黑", Font.BOLD, fontSize));
        label.setForeground(color);
        return label;
    }

    // 创建样式化按钮
    // 创建样式化按钮
    public static JButton createStyledButton(String text, Color bgColor, int width, int height) {
        JButton button = new JButton(text) {
            @Override
            protected void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 获取当前按钮状态颜色
                Color buttonColor = getBackground();

                // 绘制圆角背景
                g2.setColor(buttonColor);
                g2.fillRoundRect(0, 0, getWidth(), getHeight(), 15, 15);

                // 绘制文字
                g2.setColor(Color.WHITE);
                g2.setFont(new Font("微软雅黑", Font.BOLD, 14));
                FontMetrics fm = g2.getFontMetrics();
                int x = (getWidth() - fm.stringWidth(getText())) / 2;
                int y = (getHeight() - fm.getHeight()) / 2 + fm.getAscent();
                g2.drawString(getText(), x, y);

                g2.dispose();
            }
        };

        button.setPreferredSize(new Dimension(width, height));
        button.setBorder(BorderFactory.createEmptyBorder());
        button.setContentAreaFilled(false);
        button.setFocusPainted(false);
        button.setBackground(bgColor); // 初始背景色

        // 添加鼠标悬停与点击效果
        button.addMouseListener(new MouseAdapter() {
            private boolean isHovered = false;

            @Override
            public void mouseEntered(MouseEvent e) {
                isHovered = true;
                button.setCursor(new Cursor(Cursor.HAND_CURSOR));
                button.setBackground(bgColor.brighter());
                button.repaint();
            }

            @Override
            public void mouseExited(MouseEvent e) {
                isHovered = false;
                button.setBackground(bgColor);
                button.repaint();
            }

            @Override
            public void mousePressed(MouseEvent e) {
                button.setBackground(bgColor.darker());
                button.repaint();
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                button.setBackground(isHovered ? bgColor.brighter() : bgColor);
                button.repaint();
            }
        });

        return button;
    }

    // 创建样式化文本框
    public static JTextField createStyledTextField(int columns, Color fieldBorder, Color fieldBackground) {
        JTextField field = getStyledTextField(columns, fieldBorder);

        field.setBackground(fieldBackground);
        field.setBorder(BorderFactory.createEmptyBorder(8, 10, 8, 10));
        field.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        return field;
    }

    // 创建样式化密码框
    public static JPasswordField createStyledPasswordField(int columns, Color fieldBorder, Color fieldBackground) {
        JPasswordField field = getStyledPasswordField(columns, fieldBorder);

        field.setBackground(fieldBackground);
        field.setBorder(BorderFactory.createEmptyBorder(8, 10, 8, 10));
        field.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        return field;
    }

    private static JPasswordField getStyledPasswordField(int columns, Color fieldBorder) {
        return new JPasswordField(columns) {
            @Override
            protected void paintBorder(Graphics g) {
                GraphInner(g, fieldBorder, getWidth() - 1, getHeight() - 1);
            }
        };
    }

    private static JTextField getStyledTextField(int columns, Color fieldBorder) {
        return new JTextField(columns) {
            @Override
            protected void paintBorder(Graphics g) {
                GraphInner(g, fieldBorder, getWidth() - 1, getHeight() - 1);
            }
        };
     }

    private static void GraphInner(Graphics g, Color fieldBorder, int width, int height) {
        Graphics2D g2 = (Graphics2D) g.create();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(fieldBorder);
        g2.drawRoundRect(0, 0, width, height, 8, 8);
        g2.dispose();
    }

}
